package com.badger.spring.boot.security.config.access;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

/**
 * 接口鉴权的方法
 * @author liqi
 */
@Component("resourcePermissionService")
public class ResourcePermissionService implements ResourcePermissionProcessor {

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    public static final Map<String, List<String>> AUTH_MAP = new HashMap<>();

    static {
        AUTH_MAP.put("admin", Arrays.asList("/admin"));
        AUTH_MAP.put("ROLE_test", Arrays.asList("/test"));
    }

    @Override
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        // 当前用户所具有的权限
        final Set<String> authorityListToSet = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
        final String url = request.getRequestURI();// 当前请求的url
        for (String roleName : authorityListToSet) {
            List<String> list = AUTH_MAP.get(roleName);
            if (list != null) {
                final Optional<String> findAny = list.stream().filter(res -> {
                    // 通配符路径验证 eg: /sys/login/** --表示任意路径 "*"号
                    return antPathMatcher.match(res, url);
                }).findAny();
                if (findAny.isPresent()) {
                    return true;
                }
            }
        }
        // 异常不是鉴权异常的时候，异常无法向上抛出，异常处理的controller无法返回默认异常，需要把异常处理成鉴权异常
        throw new AuthenticationServiceException("没有访问url的权限:" + url);
    }

}
